import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/bill_entity.dart';
import 'package:finance_app/src/entities/invoice_entity.dart';
import 'package:finance_app/src/entities/leave_item_entity.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/report_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/dashboard_add_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/list_select_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

mixin ChatroomActionMixin<T> on BaseProvider<T> {
  void onActionTo(String type, String text, dynamic data) {
    if (type == 'deep_link' || type == 'push_notification') {
      String goto = data['goto'];
      Uri uri = Uri.parse(goto);
      String listString = uri.queryParameters['filter'];
      if (listString != null) {
        goto = uri.path;
      }
      String dueDate;
      // if (type == 'push_notification') {
      if (data["data"] is Map && data["data"]["filters"] != null) {
        if (goto == "purchase_bill_expense_list") {
          listString = 'Unpaid Bill';
        } else if (goto == "invoice_list") {
          listString = 'Unpaid';
        }
      }

      if (data["data"] is Map && data["data"]["due_date"] != null) {
        dueDate = data["data"]["due_date"];
      }
      // }

      int id = data['goto_id'];
      // print(text);
      // print(type);
      // print(data);
      // return;
      if (data['type'] == 'url' && goto != null) {
        launch(goto);
        return;
      }

      Map<String, VoidCallback> typeToRouterMap = {
        'logout': () {
          Config.clearConfig();
          Routes.navigateTo(RouterGenProviders.loginPage,
              clearStack: true, params: {"toastMessage": "Please login again"});
          return;
        },
        'scan': () {
          Routes.navigateTo(RouterGenProviders.ocrCameraPage);
        },
        'record': () {
          obtainContext?.call((context) async {
            showDashboardAddBottomSheet(context);
          });
        },
        'product_new': () {
          Routes.navigateTo(RouterGenProviders.newProductPage,
              params: {'id': id, 'isPro': true});
        },
        'product': () {
          Routes.navigateTo(RouterGenProviders.newProductPage,
              params: {'id': id, 'isPro': true});
        },
        'product_list': () {
          Routes.navigateTo(RouterGenProviders.productsAndServicesPage);
        },
        'product_edit': () {
          Routes.navigateTo(RouterGenProviders.newProductPage,
              params: {'id': id, 'isPro': true});
        },
        'service_new': () {
          Routes.navigateTo(RouterGenProviders.newServicePage,
              params: {'isPro': true});
        },
        'account_new': () {
          Routes.navigateTo(RouterGenProviders.addBankAccountPage);
        },
        'employee_new': () {
          Routes.navigateTo(RouterGenProviders.newEmployeePage);
        },
        'employee': () {
          Routes.navigateTo(RouterGenProviders.newEmployeePage,
              params: {'id': id});
        },
        'expense_new': () {
          Routes.navigateTo(RouterGenProviders.newExpensePage);
        },
        'reimburse_new': () {
          Routes.navigateTo(RouterGenProviders.newExpensePage);
        },
        'purchase_order_new': () {
          Routes.navigateTo(RouterGenProviders.newPurchaseOrderPage);
        },
        'bill_new': () {
          Routes.navigateTo(RouterGenProviders.newBillPage);
        },
        'cash_in_new': () {
          Routes.navigateTo(RouterGenProviders.newCashInPage);
        },
        'cash_out_new': () {
          Routes.navigateTo(RouterGenProviders.newCashOutPage);
        },
        'transfer_new': () {
          Routes.navigateTo(RouterGenProviders.newAccountTransferPage);
        },
        'debit_note_new': () {
          Routes.navigateTo(RouterGenProviders.newDebitNotePage);
        },
        'quotation_new': () {
          Routes.navigateTo(RouterGenProviders.newQuotationPage);
        },
        'invoice_new': () {
          Routes.navigateTo(RouterGenProviders.newInvoicePage);
        },
        'credit_note_new': () {
          Routes.navigateTo(RouterGenProviders.newCreditNotePage);
        },
        'contact_new': () {
          Routes.navigateTo(RouterGenProviders.newContactPersonPage);
        },
        'leave_new': () {
          Routes.navigateTo(RouterGenProviders.newLeavePage);
        },
        'coa_account_new': () {
          Routes.navigateTo(RouterGenProviders.newAccountPage);
        },
        'invite': () {
          Routes.navigateTo(RouterGenProviders.inviteTeamMembersPage);
        },
        "purchase_list": () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage,
              params: {'type': 3, 'initFilter': listString});
        },
        'purchase_order_list': () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage,
              params: {'type': 4, 'initFilter': listString});
        },
        "purchase_bill_expense_list": () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
            'type': 5,
            'initFilter': listString,
            'dueDate': dueDate
          });
        },
        "purchase_debit_note_list": () {
          Routes.navigateTo(RouterGenProviders.creditDebitPage, params: {
            'index': 1,
          });
        },
        'purchase_order': () {
          Routes.navigateTo(RouterGenProviders.newPurchaseOrderPage,
              params: {'data': TransactionEntity()..transactionableId = id});
        },
        "sales_list": () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage,
              params: {'type': 0, 'initFilter': listString});
        },
        "sales_quotation_list": () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage,
              params: {'type': 1, 'initFilter': listString});
        },
        "sales_invoice_list": () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage,
              params: {'type': 2, 'initFilter': listString});
        },
        "sales_credit_note_list": () {
          Routes.navigateTo(RouterGenProviders.creditDebitPage,
              params: {'initIndex': 0, 'initFilter': listString});
        },
        'service_list': () {
          Routes.navigateTo(RouterGenProviders.productsAndServicesPage,
              params: {
                'initIndex': 1,
              });
        },
        'service': () {
          Routes.navigateTo(RouterGenProviders.newServicePage,
              params: {'id': id, 'isPro': true});
        },
        'expense': () {
          Routes.navigateTo(RouterGenProviders.newExpensePage,
              params: {'data': TransactionEntity()..transactionableId = id});
        },
        'transaction_list': () {
          //keyword: NCS Hub
          // types:quotation,invoice,cash_in,purchase_order,bill,expense,cash_out,unpaid_out
          // status:open,closed,accepted,rejected
          // is_overdue:0
          // contact_id:1
          // start_date:2021-01-02
          // end_date:2021-10-02

          Routes.navigateTo(
            RouterGenProviders.allTransactionsPage,
          );
        },
        'invoice_list': () {
          //keyword: NCS Hub
          // types:invoice
          // status:open,closed
          // is_overdue:0
          // contact_id:1
          // start_date:2021-01-02
          // end_date:2021-10-02
          Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
            'type': 2,
            'initFilter': listString,
            'dueDate': dueDate
          });
        },
        'invoice': () {
          Routes.navigateTo(RouterGenProviders.newInvoicePage,
              params: {'data': TransactionEntity()..transactionableId = id});
        },
        'quotation_list': () {
          // keyword: NCS Hub
          // types:quotation
          // status:open,closed
          // is_overdue:0
          // contact_id:1
          // start_date:2021-01-02
          // end_date:2021-10-02
          Routes.navigateTo(
            RouterGenProviders.allTransactionsPage,
          );
        },
        'quotation': () {
          Routes.navigateTo(RouterGenProviders.newQuotationPage,
              params: {'data': TransactionEntity()..transactionableId = id});
        },
        'bill_list': () {
          Routes.navigateTo(
            RouterGenProviders.allTransactionsPage,
          );
        },
        'bill': () {
          Routes.navigateTo(RouterGenProviders.newBillPage,
              params: id != null
                  ? {'data': TransactionEntity()..transactionableId = id}
                  : null);
        },
        'employee_list': () {
          Routes.navigateTo(
            RouterGenProviders.employeeContactsPage,
          );
        },
        'product_activate': () {
          Routes.navigateTo(RouterGenProviders.batchProductsAndServicesPage,
              params: {
                'isService': false,
                'type': 'Activate',
              });
        },
        'product_deactivate': () {
          Routes.navigateTo(RouterGenProviders.batchProductsAndServicesPage,
              params: {
                'isService': false,
                'type': 'Deactivate',
              });
        },
        'service_edit': () {
          Routes.navigateTo(RouterGenProviders.newServicePage, params: {});
        },
        'service_deactivate': () {
          Routes.navigateTo(RouterGenProviders.batchProductsAndServicesPage,
              params: {
                'isService': true,
                'type': 'Deactivate',
              });
        },
        'service_activate': () {
          Routes.navigateTo(RouterGenProviders.batchProductsAndServicesPage,
              params: {
                'isService': true,
                'type': 'Activate',
              });
        },
        'account_list': () {
          Routes.navigateTo(RouterGenProviders.cashAndBankPage, params: {});
        },
        'expense_list': () {
          Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
            'type': 6,
            'initFilter': listString,
            'dueDate': dueDate
          });
        },
        'payment_out_new': () {
          Routes.navigateTo(RouterGenProviders.newCashOutPage, params: {
            'billList': <BillEntity>[],
          });
        },
        'payment_in_new': () {
          Routes.navigateTo(RouterGenProviders.newCashInPage, params: {
            'invoiceList': <InvoiceEntity>[],
          });
        },
        'payment_list': () {
          Routes.navigateTo(RouterGenProviders.allPaymentPage, params: {
            'accountId': null,
            'accountName': null,
          });
        },
        'transfer_list': () {
          Routes.navigateTo(RouterGenProviders.allPaymentPage, params: {
            'accountId': null,
            'accountName': null,
          });
        },
        'debit_note_list': () {
          Routes.navigateTo(RouterGenProviders.creditDebitPage, params: {
            'index': 1,
          });
        },
        'credit_note_list': () {
          Routes.navigateTo(RouterGenProviders.creditDebitPage, params: {
            'initIndex': 0,
          });
        },
        'business_contact_new': () {
          Routes.navigateTo(RouterGenProviders.businessContactProfilePage,
              params: {});
        },
        'business_contact_list': () {
          Routes.navigateTo(RouterGenProviders.mainBusinessContactPage,
              params: {
                'initFilter': listString,
              });
        },
        'inventory_adjust': () {
          Routes.navigateTo(RouterGenProviders.adjustInventoryListPage,
              params: {
                'status': 'Active',
              });
        },
        //HR
        'payslip_generate': () {
          Routes.navigateTo(RouterGenProviders.employeeBatchSelectPage,
              params: {
                'pageTitle': S.current.generate_payslip,
              });
        },
        'employee_left': () {
          Routes.navigateTo(RouterGenProviders.markAsResignedPage);
        },
        'payslip_new': () {
          Routes.navigateTo(RouterGenProviders.payrollPaymentPage, params: {});
        },
        'payslip_payment': () {
          Routes.navigateTo(RouterGenProviders.payrollPaymentPage, params: {});
        },
        'leave_adjust': () {
          Routes.navigateTo(RouterGenProviders.leaveAdjustmentPage, params: {});
        },
        'claim_new': () {
          Routes.navigateTo(RouterGenProviders.newExpensePage, params: {
            'isSelectMode': true,
            'isHidePaid': true,
          });
        },
        'leave_approval': () {
          Routes.navigateTo(RouterGenProviders.leaveOperationPage, params: {
            'operation': 'Approve',
          });
        },
        'leave_reject': () {
          Routes.navigateTo(RouterGenProviders.leaveOperationPage, params: {
            'operation': 'Reject',
          });
        },
        'leave_list': () {
          Routes.navigateTo(RouterGenProviders.hrAndPayrollPage, params: {
            'initIndex': 3,
            'isSelectEmployee': true,
          });
        },
        'claim_approval': () {
          Routes.navigateTo(RouterGenProviders.reimburseApprovePage, params: {
            'operation': 'Approve',
          });
        },
        'claim_reject': () {
          Routes.navigateTo(RouterGenProviders.reimburseApprovePage, params: {
            'operation': 'Reject',
          });
        },
        'claim_list': () {
          Routes.navigateTo(RouterGenProviders.hrAndPayrollPage, params: {
            'initIndex': 2,
          });
        },
        'team_invite_from_employee': () {
          Routes.navigateTo(RouterGenProviders.inviteTeamMembersPage, params: {
            'isSelectEmployee': true,
          });
        },
        'team_invite_from_phone_book': () {
          Routes.navigateTo(RouterGenProviders.inviteTeamMembersPage, params: {
            'isSelectPhoneBook': true,
          });
        },
        'team_invitation': () {
          Routes.navigateTo(RouterGenProviders.inviteTeamMembersPage, params: {
            'isSelectManually': true,
          });
        },
        'team_change_role': () {
          Routes.navigateTo(RouterGenProviders.inviteTeamMembersPage,
              params: {});
        },
        'report': () {
          Routes.navigateTo(RouterGenProviders.dateReportPage, params: {
            'type': id,
          });
        },
        // setting
        'company_settings_edit': () {
          Routes.navigateTo(RouterGenProviders.companyProfilePage, params: {
            'data': Config.currentCompany,
          });
        },
        'subscription_view': () {
          Routes.navigateTo(RouterGenProviders.subscriptionPage, params: {});
        },
        'mobile_no_edit': () {
          Routes.navigateTo(RouterGenProviders.updatePhoneNumberPage,
              params: {});
        },
        'password_edit': () {
          Routes.navigateTo(RouterGenProviders.changePasswordPage, params: {});
        },
        'profile_edit': () {
          Routes.navigateTo(RouterGenProviders.accountSettingsPage, params: {});
        },
        'biometric_edit': () {
          Routes.navigateTo(RouterGenProviders.accountSettingsPage, params: {});
        },
        'GST_setting': () {
          Routes.navigateTo(RouterGenProviders.gstPage, params: {});
        },
        'subscription_edit': () {
          Routes.navigateTo(RouterGenProviders.subscriptionPage, params: {});
        },
        'language_edit': () {
          obtainContext?.call((context) async {
            await showLanguageSelectBottomSheet(context, Config.languageCode);
          });
        },
        'number_format_edit': () {
          Routes.navigateTo(RouterGenProviders.numberFormatPage, params: {});
        },
        'preference_edit': () {
          Routes.navigateTo(RouterGenProviders.preferencesPage, params: {});
        },
        'leave': () {
          Routes.navigateTo(RouterGenProviders.newLeavePage,
              params: {'data': LeaveItemEntity()..id = id});
        },
        'report_f5': () {
          Routes.navigateTo(RouterGenProviders.dateReportPage,
              params: {'type': ReportUtils.gstF5});
        },
      };
      String requiredPermission;
      switch (goto) {
        case 'quotation_new':
        case 'sales_quotation_list':
        case 'quotation_list':
        case 'quotation':
          requiredPermission = PermissionUtils.quotation;
          break;
        case 'invoice_new':
        case 'sales_invoice_list':
        case 'invoice_list':
          requiredPermission = PermissionUtils.invoice;
          break;
        case 'purchase_order_new':
        case 'purchase_order_list':
        case 'purchase_order':
          requiredPermission = PermissionUtils.purchaseOrder;
          break;
        case 'bill_new':
        case 'bill_list':
        case 'bill':
          requiredPermission = PermissionUtils.bill;
          break;
        case 'expense_new':
        case 'scan':
        // case 'expense': //allow employee can view claim
        case 'expense_list':
          requiredPermission = PermissionUtils.expense;
          break;
        case 'debit_note_new':
        case 'credit_note_new':
        case 'purchase_debit_note_list':
        case 'sales_credit_note_list':
        case 'debit_note_list':
        case 'credit_note_list':
          requiredPermission = PermissionUtils.creditDebitNote;
          break;
        case 'product_new':
        case 'product_new':
        case 'product':
        case 'product_list':
        case 'product_edit':
        case 'service_new':
        case 'service_list':
        case 'service':
        case 'product_activate':
        case 'product_deactivate':
        case 'service_edit':
        case 'service_deactivate':
        case 'service_activate':
        case 'inventory_adjust':
          requiredPermission = PermissionUtils.productService;
          break;
        case 'contact_new':
        case 'business_contact_new':
        case 'business_contact_list':
          requiredPermission = PermissionUtils.businessContact;
          break;
        case 'account_new':
        case 'cash_in_new':
        case 'cash_out_new':
        case 'transfer_new':
        case 'account_list':
        case 'payment_out_new':
        case 'payment_in_new':
        case 'payment_list':
        case 'transfer_list':
          requiredPermission = PermissionUtils.cashBank;
          break;
        case 'employee_list':
        case 'payslip_generate':
        case 'employee_left':
        case 'payslip_new':
        case 'payslip_payment':
        case 'leave_adjust':
        case 'leave_approval':
        case 'leave_reject':
        case 'leave_list':
        case 'claim_approval':
        case 'claim_reject':
        case 'claim_list':
        case 'employee_new':
          requiredPermission = PermissionUtils.hrPayroll;
          break;
        case 'coa_account_new':
          requiredPermission = PermissionUtils.chartOfAccounts;
          break;
        case 'company_settings_edit':
        case 'GST_setting':
        case 'number_format_edit':
        case 'preference_edit':
          requiredPermission = PermissionUtils.companySettings;
          break;
        case 'invite':
        case 'team_invite_from_employee':
        case 'team_invite_from_phone_book':
        case 'team_invitation':
        case 'team_change_role ':
          requiredPermission = PermissionUtils.inviteTeamMembers;
          break;
        case 'report':
          if (ReportUtils.isSalesReport(id)) {
            requiredPermission = PermissionUtils.salesReport;
          } else if (ReportUtils.isPurchasesReport(id)) {
            requiredPermission = PermissionUtils.purchaseReports;
          } else if (ReportUtils.isInventoryReport(id)) {
            requiredPermission = PermissionUtils.inventoryReports;
          } else if (ReportUtils.isHRReport(id)) {
            requiredPermission = PermissionUtils.hrPayrollReports;
          } else if (ReportUtils.isTaxReport(id)) {
            requiredPermission = PermissionUtils.taxesReports;
          } else if (ReportUtils.isAccountantReport(id)) {
            requiredPermission = PermissionUtils.accountantReports;
          }
          break;
        default:
      }

      if (requiredPermission != null &&
          !Config.hasPermission(requiredPermission)) {
        obtainContext((context) {
          showNoPermission(context);
        });
        return;
      }

      if (Config.myPermission.canEdit != 0 &&
          (goto == 'subscription_view' || goto == 'subscription_edit')) {
        obtainContext((context) {
          showNoPermission(context);
        });
        return;
      }

      typeToRouterMap[goto]?.call();
    }
  }
}
